package com.uroad.liaoningpos.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.boc.aidl.printer.AidlPrinter;
import com.boc.aidl.printer.AidlPrinterListener;
import com.uroad.liaoningpos.R;
import com.uroad.liaoningpos.common.BaseActivity;
import com.uroad.liaoningpos.common.PrintServiceResult;
import com.uroad.liaoningpos.common.SPContants;
import com.uroad.liaoningpos.model.MessageEvent;
import com.uroad.liaoningpos.model.SettleAccountMDL;
import com.uroad.liaoningpos.util.BitmapUtil;
import com.uroad.liaoningpos.util.SPUtils;
import com.uroad.liaoningpos.webService.PosWS;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.util.file.SDUtil;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.util.string.StringUtils;
import com.uroad.lib.widget.dialog.DialogHelper;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @创建者 wlw
 * @创建时间 2019/4/2 20:51
 * @描述 换班结算
 */
public class SettleAccountsActivity extends BaseActivity {
    private static String TAG = "SettleAccountsActivity";

    @BindView(R.id.tvBeonduty)
    TextView tvBeonduty;
    @BindView(R.id.tvTimeCreate)
    TextView tvTimeCreate;
    @BindView(R.id.tvTimeEnd)
    TextView tvTimeEnd;
    @BindView(R.id.tvMerchantName)
    TextView tvMerchantName;
    @BindView(R.id.tvMerchantNo)
    TextView tvMerchantNo;
    @BindView(R.id.tvMerchantNozl)
    TextView tvMerchantNozl;
    @BindView(R.id.tvTerminalNo)
    TextView tvTerminalNo;
    @BindView(R.id.tvTerminalNozl)
    TextView tvTerminalNozl;
    @BindView(R.id.tvHighWayAmount)
    TextView tvHighWayAmount;
    @BindView(R.id.tvCreditDeduction)
    TextView tvCreditDeduction;
    @BindView(R.id.tvActualPayment)
    TextView tvActualPayment;
    @BindView(R.id.tvUnionAmount)
    TextView tvUnionAmount;
    @BindView(R.id.tvwxAmount)
    TextView tvwxAmount;
    @BindView(R.id.tvaliAmount)
    TextView tvaliAmount;
    @BindView(R.id.tvSwipeAmount)
    TextView tvSwipeAmount;
    @BindView(R.id.tvTotal)
    TextView tvTotal;
    @BindView(R.id.btnPrint)
    TextView btnPrint;
    @BindView(R.id.btnSettle)
    TextView btnSettle;


    //打印模块
    @BindView(R.id.llPrintLayout)
    LinearLayout llPrintLayout;
    @BindView(R.id.tvBeondutyP)
    TextView tvBeondutyP;//班次号
    @BindView(R.id.tvTimeCreateP)
    TextView tvTimeCreateP;//换班时间
    @BindView(R.id.tvTimeEndP)
    TextView tvTimeEndP;//换班时间
    @BindView(R.id.tvMerchantNameP)
    TextView tvMerchantNameP;//商户名称
    @BindView(R.id.tvMerchantNoP)
    TextView tvMerchantNoP;//商户编号
    @BindView(R.id.tvMerchantNoPzl)
    TextView tvMerchantNoPzl;//商户编号
    @BindView(R.id.tvTerminalNoP)
    TextView tvTerminalNoP;//终端编号
    @BindView(R.id.tvTerminalNoPzl)
    TextView tvTerminalNoPzl;//终端编号
    @BindView(R.id.tvHighWayAmountP)
    TextView tvHighWayAmountP;//高速付款码
    @BindView(R.id.tvCreditDeductionP)
    TextView tvCreditDeductionP;//高速付款码
    @BindView(R.id.tvActualPaymentP)
    TextView tvActualPaymentP;//高速付款码
    @BindView(R.id.tvUnionAmountP)
    TextView tvUnionAmountP;//银联付款码
    @BindView(R.id.tvwxAmountP)
    TextView tvwxAmountP;//微信付款码
    @BindView(R.id.tvaliAmountP)
    TextView tvaliAmountP;//支付宝付款码
    @BindView(R.id.tvSwipeAmountP)
    TextView tvSwipeAmountP;//刷卡
    @BindView(R.id.tvTotalP)
    TextView tvTotalP;//总计

    @BindView(R.id.linearLayout11_2)
    LinearLayout linearLayout11_2;
    @BindView(R.id.linearLayout11_3)
    LinearLayout linearLayout11_3;
    @BindView(R.id.linearLayout11_2P)
    LinearLayout linearLayout11_2P;
    @BindView(R.id.linearLayout11_3P)
    LinearLayout linearLayout11_3P;


    private String posimei;

    private SimpleDateFormat sfym = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private String path = "";

    private AidlPrinter printerModule;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayout(R.layout.activity_settle_accounts);
        ButterKnife.bind(this);
        setTitle("换班结算");
        linearLayout11_2.setVisibility(View.GONE);
        linearLayout11_2P.setVisibility(View.GONE);
        linearLayout11_3.setVisibility(View.GONE);
        linearLayout11_3P.setVisibility(View.GONE);
        setData();
        loadData();
        bindDeviceService();
    }

    @Override
    protected void bindDeviceServiceSuccess() {
        super.bindDeviceServiceSuccess();
        try {
            printerModule = AidlPrinter.Stub.asInterface(deviceService.getPrinter());
        } catch (RemoteException e) {
            e.printStackTrace();
            LogUtil.i(TAG, "获取打印模块异常");
        }
    }

    private void setData() {
        posimei = (String) SPUtils.get(this, SPContants.SP_IMEI, "");
        String merchantId = (String) SPUtils.get(this, SPContants.SP_MERCHANTNO, "");
        String merchantIdzhilian = (String) SPUtils.get(this, SPContants.SP_MERCHANTNO_ZHILIAN, "");
        String shopName = (String) SPUtils.get(this, SPContants.SP_SHOPNAME, "");
        String imei = (String) SPUtils.get(this, SPContants.SP_TERMINALNO, "");
        String imeizhilan = (String) SPUtils.get(this, SPContants.SP_TERMINALNO_ZHILIAN, "");
        String beonduty = (String) SPUtils.get(this, SPContants.SP_BEONDUTY, "");

        Date selectDate = new Date();
        String date = sfym.format(selectDate);

        tvBeonduty.setText(beonduty);
        tvTimeEnd.setText(date);
        tvMerchantName.setText(shopName);
        tvMerchantNo.setText(merchantId);
        tvMerchantNozl.setText(merchantIdzhilian);
        tvTerminalNo.setText(imei);
        tvTerminalNozl.setText(imeizhilan);

        tvBeondutyP.setText(beonduty);
        tvTimeEndP.setText(date);
        tvMerchantNameP.setText(shopName);
        tvMerchantNoP.setText(merchantId);
        tvMerchantNoPzl.setText(merchantIdzhilian);
        tvTerminalNoP.setText(imei);
        tvTerminalNoPzl.setText(imeizhilan);

    }

    private void loadData() {
        //TODO 获取换班结算数据
        DialogHelper.showLoading(this,"结算汇总中");
        String ticketid = (String) SPUtils.get(this, SPContants.SP_TICKETID, "");
        String deviceuuid = (String) SPUtils.get(this, SPContants.SP_DEVICEUUID, "");
        String beonduty = (String) SPUtils.get(this, SPContants.SP_BEONDUTY, "");
        doRequest(PosWS.paylogout, PosWS.paylogoutParams(ticketid, deviceuuid, posimei, beonduty), PosWS.paylogout);
    }
    private void settle(){
        String str = "payment://com.newland.pospp/settle";
        Uri uri = Uri.parse(str);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivityForResult(intent, 1);
    }
    @OnClick({R.id.btnSettle,R.id.btnPrint})
    public void onClick(View view) {//登出
        switch (view.getId()) {
            case R.id.btnSettle:
                settle();
//                DialogHelper.showLoading(this,"正在退出");
//                String ticketid = (String) SPUtils.get(this, SPContants.SP_TICKETID, "");
//                String deviceuuid = (String) SPUtils.get(this, SPContants.SP_DEVICEUUID, "");
//                doRequest(PosWS.logout, PosWS.logoutParams(ticketid, deviceuuid), PosWS.logout);
                break;
            case R.id.btnPrint:
                DialogHelper.showLoading(this,"正在打印中");
                print();
                break;
        }
    }

    private void print() {
        //TODO 重打印
        if (SDUtil.isExistSD()) {
            try {
                Bitmap bitmap = BitmapUtil.createBitmap(llPrintLayout);
                //            path = BitmapUtil.viewSaveToImage(llPrintLayout, SDUtil.createDir("LiaoNingPos"), "print.PNG",true);
                printerModule.printBitMap(0, bitmap, 30, new AidlPrinterListener.Stub() {
                    @Override
                    public void onError(int code, String mess) throws RemoteException {
                        DialogHelper.endLoading();
                        showShortToast(mess);
                        Log.d("LOG", "打印失败：" + mess);//具体的code见ServiceResult
                    }

                    @Override
                    public void onFinish() throws RemoteException {
                        DialogHelper.endLoading();
                        printerModule.paperSkip(2);
                        showShortToast("打印成功");

                    }
                });
            } catch (RemoteException e) {
                e.printStackTrace();
                LogUtil.i(TAG, "图片打印异常");
            } catch (Exception e) {
                e.printStackTrace();
            }
            //            //view转bitmap并保存在本地
            //            new Thread(new Runnable() {
            //                @Override
            //                public void run() {
            //                    AppHelper.callPrint(SettleAccountsActivity.this, path);
            //                }
            //            }).start();
        }else{
            showShortToast("打印失败，未检测到存储设备");
        }
    }

    @Override
    public void OnHttpTaskComplete(String result, String id) {
        super.OnHttpTaskComplete(result, id);
        DialogHelper.endLoading();
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (FastJsonUtils.getJsonStatu00(jsonObject)) {
            if (PosWS.paylogout.equalsIgnoreCase(id)) {
                SettleAccountMDL accountMDL = FastJsonUtils.parseDataObjectJSON(jsonObject, SettleAccountMDL.class);
                if (accountMDL != null) {
                    List<SettleAccountMDL.PayList> payLists = accountMDL.getPaylist();
                    tvHighWayAmount.setText("0.00");
                    tvUnionAmount.setText("0.00");
                    tvwxAmount.setText("0.00");
                    tvaliAmount.setText("0.00");
                    tvSwipeAmount.setText("0.00");
                    tvHighWayAmountP.setText("0.00");
                    tvUnionAmountP.setText("0.00");
                    tvwxAmountP.setText("0.00");
                    tvaliAmountP.setText("0.00");
                    tvSwipeAmountP.setText("0.00");
                    tvTotal.setText(StringUtils.divideHundred(accountMDL.getAmountsum()));
                    tvTotalP.setText(StringUtils.divideHundred(accountMDL.getAmountsum()));
                    tvTimeCreate.setText(accountMDL.getCreated());
                    tvTimeCreateP.setText(accountMDL.getCreated());
                    if (payLists != null && payLists.size() > 0) {
                        for (SettleAccountMDL.PayList pay : payLists) {
                            if ("1".equalsIgnoreCase(pay.getType())) {
                                //刷卡
                                if (!TextUtils.isEmpty(pay.getAmount())) {
                                    tvSwipeAmount.setText(StringUtils.divideHundred(pay.getAmount()));
                                    tvSwipeAmountP.setText(StringUtils.divideHundred(pay.getAmount()));
                                }else{
                                    tvSwipeAmount.setText("0.00");
                                    tvSwipeAmountP.setText("0.00");
                                }
                            } else if ("2".equalsIgnoreCase(pay.getType())) {
                                //银联码
                                if(!TextUtils.isEmpty(pay.getAmount())) {
                                    tvUnionAmount.setText(StringUtils.divideHundred(pay.getAmount()));
                                    tvUnionAmountP.setText(StringUtils.divideHundred(pay.getAmount()));
                                }else{
                                    tvUnionAmount.setText("0.00");
                                    tvUnionAmountP.setText("0.00");
                                }
                            } else if ("3".equalsIgnoreCase(pay.getType())) {
                                //高速通码
                                if(!TextUtils.isEmpty(pay.getAmount())) {
                                    tvHighWayAmount.setText(StringUtils.divideHundred(pay.getAmount()));
                                    tvHighWayAmountP.setText(StringUtils.divideHundred(pay.getAmount()));
                                }else {
                                    tvHighWayAmount.setText("0.00");
                                    tvHighWayAmountP.setText("0.00");
                                }
                            }else if ("4".equalsIgnoreCase(pay.getType())) {
                                //微信码
                                if(!TextUtils.isEmpty(pay.getAmount())) {
                                    tvwxAmount.setText(StringUtils.divideHundred(pay.getAmount()));
                                    tvwxAmountP.setText(StringUtils.divideHundred(pay.getAmount()));
                                }else {
                                    tvwxAmount.setText("0.00");
                                    tvwxAmountP.setText("0.00");
                                }
                            }else if ("5".equalsIgnoreCase(pay.getType())) {
                                //支付宝码
                                if(!TextUtils.isEmpty(pay.getAmount())) {
                                    tvaliAmount.setText(StringUtils.divideHundred(pay.getAmount()));
                                    tvaliAmountP.setText(StringUtils.divideHundred(pay.getAmount()));
                                }else {
                                    tvaliAmount.setText("0.00");
                                    tvaliAmountP.setText("0.00");
                                }
                            }
                        }
                        tvTotal.setText(StringUtils.divideHundred(accountMDL.getAmountsum()));
                        tvTotalP.setText(StringUtils.divideHundred(accountMDL.getAmountsum()));
                    }else{

                    }
                }else{
                    showShortToast("结算失败");
                }
            } else if (PosWS.logout.equalsIgnoreCase(id)) {
                openActivity(LoginActivity.class);
                EventBus.getDefault().post(new MessageEvent("close"));
                finish();
            }
        }else{
            showShortToast(FastJsonUtils.getErrMsg00(jsonObject));
        }
    }

    @Override
    public void OnHttpNetWork(String msg) {
        super.OnHttpNetWork(msg);
        DialogHelper.endLoading();
    }

    @Override
    public void OnHttpFailure(String msg) {
        super.OnHttpFailure(msg);
        DialogHelper.endLoading();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        DialogHelper.endLoading();
        if(-1 == resultCode){
//            showPrintResult(data.getStringExtra("resultCode") + "");
//            Log.d("LOG", data.getStringExtra("resultCode")+"");//具体的code见ServiceResult
            DialogHelper.showLoading(this,"正在退出");
            String ticketid = (String) SPUtils.get(this, SPContants.SP_TICKETID, "");
            String deviceuuid = (String) SPUtils.get(this, SPContants.SP_DEVICEUUID, "");
            doRequest(PosWS.logout, PosWS.logoutParams(ticketid, deviceuuid), PosWS.logout);
        }
    }

    private void showPrintResult(String resultCode) {
        if (!TextUtils.isEmpty(resultCode)) {
            String result = PrintServiceResult.getResult(resultCode);
            showShortToast(result);
        }
    }

}
